package com.tsystems.train.bean;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;

import com.tsystems.train.entity.Train;
import com.tsystems.train.service.TrainServices;
import com.tsystems.train.validator.MyValidator;

@Named("trainTableBean")
@RequestScoped
public class TrainTableBean implements Serializable {

	private static final long serialVersionUID = 2165793273424547096L;

	@EJB
	private TrainServices trainService;

	private String number;
	private String seats;
	private TrainTableDataModel trainTableDataModel;
	private Train selectedTrain = new Train();

	public TrainTableBean() {
		trainTableDataModel = new TrainTableDataModel();
		selectedTrain = new Train();
	}

	@PostConstruct
	public void init() {
		updateTable();
	}

	public void updateTable() {
		List<Train> result = trainService.viewTrains();
		trainTableDataModel.setWrappedData(result);

	}

	public String addTrain() {

		try {
			number.trim();

			long seatL = Long.parseLong(seats);
			Train train = new Train(number, seatL);
			if (!MyValidator.validate(train)) {
				return null;
			}
			String result = trainService.addTrain(train);
			if (result.equals("New train added")) {
				updateTable();
				FacesMessage message = new FacesMessage(
						FacesMessage.SEVERITY_INFO, "Info", result);

				FacesContext.getCurrentInstance().addMessage(null, message);
			} else {
				FacesMessage message = new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Error", result);

				FacesContext.getCurrentInstance().addMessage(null, message);
			}
		} catch (NumberFormatException e) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Train add error",
					"Seats must be integer.");

			FacesContext.getCurrentInstance().addMessage(null, message);
		}
		return null;
	}

	public Train getSelectedTrain() {
		return selectedTrain;
	}

	public void setSelectedTrain(Train selectedTrain) {
		this.selectedTrain = selectedTrain;
	}

	public TrainTableDataModel getTrainTableDataModel() {
		return trainTableDataModel;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public String getSeats() {
		return seats;
	}

	public void setSeats(String seats) {
		this.seats = seats;
	}

}
